import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'
import {
  getToken,
  removeToken,
  setToken
} from './auth'
import router from '../router';



const myheader = 'pacargle';

// create an axios instance
const service = axios.create({
  // 发起axios请求，在生成环境里，配置了这个baseURL，然后配置代理服务，解决了跨域问题。 配置代理在 /vue.config.js devServer{proxy:{}}
  baseURL: process.env.VUE_APP_BASE_API, 
  
  timeout: 20000 // request timeout
})
//https://bs.pacargle.com:221
// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  config.headers[myheader] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
 
 // config.headers.pacargle = 'eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NTM0NjcyODIsImV4cCI6MTY1MzQ3NDQ4MiwibWFuZ2VySWQiOjEsIm5pY2tOYW1lIjoi6LaF57qn566h55CG5ZGYIiwicm9sZUlkIjoxLCJyZWZyZXNoQ291bnQiOjAsImxvZ2luTmFtZSI6ImFkbWluIn0.nVbdlFG9UEwpU71sPv14Hl1qMe8t2ABoVV362SVdbjM'
  //  config.headers = {
  //    'pacargle':'eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NTM0NjkzOTQsImV4cCI6MTY1MzQ3NjU5NCwibWFuZ2VySWQiOjEsIm5pY2tOYW1lIjoi6LaF57qn566h55CG5ZGYIiwicm9sZUlkIjoxLCJyZWZyZXNoQ291bnQiOjAsImxvZ2luTmFtZSI6ImFkbWluIn0.PzET4ew4uNwszDuxn-PvnD2cTI0E9GVV-3Ehbtj5GR0'
  //  } 
 return config
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Message.error({
    message: '请求超时!'
  });
  return Promise.resolve(err);
})

// respone interceptor
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    if (response.headers[myheader]) {
      setToken(response.headers[myheader]);
    }
    const res = response.data;
    if (res.errcode !== '0x0000') {
      Message({
        message: res.errmsg,
        type: 'error',
        duration: 1 * 1000
      });
      // 0x0004:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.errcode === '0x0004' && getToken()) {
        removeToken();
        MessageBox.alert('你登陆时间已到期，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          callback: action => {
            router.push({
              path: '/login'
            });
          }
        });
      }
      return Promise.reject('error');
    } else {
      return response.data;
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
